package com.mlink.ai.chat.ui.fragment

import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.mlink.ai.chat.assistant.robot.R
import com.mlink.ai.chat.assistant.robot.databinding.FragmentExploreCategoryBinding
import com.mlink.ai.chat.bean.ExploreCategory
import com.mlink.ai.chat.bean.ExploreSubCategory
import com.mlink.ai.chat.constants.KEY_CHAT_PROMPT
import com.mlink.ai.chat.ui.activity.ChatActivity
import com.mlink.ai.chat.ui.activity.PromptCreateActivity
import com.mlink.ai.chat.ui.adapter.ExploreSubCategoryAdapter
import com.mlink.ai.chat.ui.viewmodel.ExploreViewModel
import com.mlink.ai.chat.utils.*

private const val ARG_CATEGORY = "category"

class ExploreCategoryFragment : BaseFragment<FragmentExploreCategoryBinding>() {

    private var category: ExploreCategory? = null

    private var spanCount = 2

    private var subCategoryLoggedList = mutableListOf<Long>() // 已经打过的点，存储 ExploreSubCategory id


    private val viewModel: ExploreViewModel by lazy {
        ViewModelProvider(requireActivity())[ExploreViewModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            category = it.getParcelable(ARG_CATEGORY)
        }
    }

    override fun getViewBinding(): FragmentExploreCategoryBinding {
        return FragmentExploreCategoryBinding.inflate(LayoutInflater.from(context))
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.recyclerView.apply {

            layoutManager = GridLayoutManager(context, spanCount)
            addItemDecoration(
                GridSpacingItemDecoration(
                    spanCount,
                    context.resources.getDimensionPixelSize(R.dimen.explore_list_item_horizontal_spacing),
                    context.resources.getDimensionPixelSize(R.dimen.explore_list_item_vertical_spacing)
                )
            )
            adapter = ExploreSubCategoryAdapter().apply {
                setOnItemOperateListener(object :
                    ExploreSubCategoryAdapter.OnItemOperateListener {
                    override fun onCreateItemClicked() {
                        startActivity(Intent(requireContext(), PromptCreateActivity::class.java).apply {
                            putExtra(PromptCreateActivity.EXTRA_CATEGORY_ID, category?.id)
                        })
                        AnalyticsEvents.AC_EXP_PPT_CREATE_CLICK.logEvent(Bundle().apply {
                            putString(AnalyticsParams.CATEGORY, category?.categoryEventName)
                        })
                    }

                    override fun deleteItem(position: Int, subCategory: ExploreSubCategory) {
                        context?.let {
                            viewModel.getAllCategory(it)
                        }
                    }

                    override fun onItemClicked(subCategory: ExploreSubCategory) {
                        startActivity(Intent(requireContext(), ChatActivity::class.java).apply {
                            putExtra(KEY_CHAT_PROMPT, subCategory.prompt)
                        })

                        AnalyticsEvents.AC_EXP_PPT_CLICK.logEvent(Bundle().apply {

                            val type = if (subCategory.isCustom) "custom" else "preset"
                            putString(AnalyticsParams.CATEGORY, category?.categoryEventName)
                            putString(AnalyticsParams.KEY_TITLE, subCategory.categoryEventName)
                            putString(AnalyticsParams.KEY_TYPE, type)
                        })
                    }

                    override fun onDeleteShow(view: View) {
                        val fragment = parentFragment as? ExploreFragment
                        fragment?.let {
                            it.deleteView?.isVisible = false
                            it.deleteView = view
                        }
                    }

                })

                addOnScrollListener(object : OnScrollListener() {
                    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                        super.onScrollStateChanged(recyclerView, newState)

                        computeItemsVisibleRect(recyclerView)

                    }
                })
                submitList(category?.subCategories ?: ArrayList())
            }
            post {
                computeItemsVisibleRect(this)
            }
        }

    }

    override fun onDestroyView() {
        val fragment = parentFragment as? ExploreFragment
        fragment?.deleteView = null
        super.onDestroyView()
    }

    private fun computeItemsVisibleRect(recyclerView: RecyclerView) {
        val layoutManager = recyclerView.layoutManager
        if (layoutManager is GridLayoutManager) {
            val visibleRect = Rect()
            recyclerView.getGlobalVisibleRect(visibleRect)
            for (i in 0 until layoutManager.childCount) {
                val child = layoutManager.getChildAt(i)
                if (child != null) {
                    val adapterPosition = layoutManager.getPosition(child)
                    if (adapterPosition != RecyclerView.NO_POSITION) {
                        val itemRect = Rect()
                        child.getGlobalVisibleRect(itemRect)
                        val visibleHeight = itemRect.height() * 2 / 3 // item 自身高度的 2/3
                        if (itemRect.intersect(visibleRect) && itemRect.height() >= visibleHeight) {
                            // item 在屏幕上可见了自身高度的 2/3
                            val list = category?.subCategories ?: ArrayList()
                            if (adapterPosition in list.indices) {
                                val subCategory = list[adapterPosition]
                                val subCategoryId = subCategory.id
                                if (!subCategoryLoggedList.contains(subCategoryId)) {
                                    if (subCategoryId != PromptUtils.PROMPT_CREATE_ITEM_ID) {
                                        AnalyticsEvents.AC_EXP_PPT_SHOW.logEvent(Bundle().apply {
                                            putString(
                                                AnalyticsParams.CATEGORY,
                                                category?.categoryEventName
                                            )
                                            putString(AnalyticsParams.KEY_TITLE, subCategory.categoryEventName)
                                            val type =
                                                if (subCategory.isCustom) "custom" else "preset"
                                            putString(AnalyticsParams.KEY_TYPE, type)
                                        })
                                    } else {
                                        AnalyticsEvents.AC_EXP_PPT_CREATE_SHOW.logEvent(Bundle().apply {
                                            putString(
                                                AnalyticsParams.CATEGORY,
                                                category?.categoryEventName
                                            )
                                        })
                                    }
                                    subCategoryLoggedList.add(subCategoryId)
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            subCategoryLoggedList.clear()
        } else {
            binding.recyclerView.post {
                computeItemsVisibleRect(binding.recyclerView)
            }
        }
    }

    companion object {
        fun newInstance(category: ExploreCategory) =
            ExploreCategoryFragment().apply {
                arguments = Bundle().apply {
                    putParcelable(ARG_CATEGORY, category)
                }
            }
    }
}